<?php
namespace common\tools;

use Yii;
use yii\log\Logger;
/**
 * Description of HttpTool
 * 网络请求相关工具
 * @author weiwangw
 */
class HttpTool {
    //post请求
    public static function http_post($url,$postData){
        if(self::is_allow_url_fopen()){
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url); 
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); 
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); 
            curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)'); 
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
            curl_setopt($ch, CURLOPT_AUTOREFERER, 1); 
            curl_setopt($ch, CURLOPT_POSTFIELDS,$postData); 
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
            $tmpInfo = curl_exec($ch); 
            if (curl_errno($ch)) {  
                Yii::getLogger()->log(curl_error($ch), Logger::LEVEL_ERROR);
                return false;
            }else{
                curl_close($ch); 
                return $tmpInfo;
            }
        }
    }
    /**
     * get
     * @return boolean
     */
    public static function http_get($url) {
        if(self::is_allow_url_fopen()){
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_TIMEOUT, 500);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($curl, CURLOPT_URL, $url);

            $res = curl_exec($curl);
            curl_close($curl);

             return $res;        
        }
    }
    private static function is_allow_url_fopen(){
        if (ini_get('allow_url_fopen') == 1 && function_exists('curl_init')){
           return true;
        }else{
            Yii::getLogger()->log('空间不支持！请询问空间商是否开启curl和allow_url_fopen', Logger::LEVEL_ERROR);  
            return false;
        }
    }
}
